/********************************************************************************
 * UserLoginAction.java
 *
 * Created by Jigar Mistry
 * Last modified Date: Aug 26, 2008 10:57:46 AM by Jigar Mistry
 * Version : 0.1
 * Copyright (c) 2008 - 2009 cyberThink Infotech Pvt. Ltd., All rights reserved.
 ********************************************************************************/

package com.printeverywhere.action;

import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.printeverywhere.delegator.UserServiceDelegator;
import com.printeverywhere.dto.User;
import com.printeverywhere.util.AttributeConstants;
import com.printeverywhere.util.CommonUtil;
import com.printeverywhere.util.SearchCriteria;

/**
 * The Class UserLoginAction.
 */
public class UserLoginAction extends FrontBaseSupport implements
		ServletRequestAware, ServletResponseAware {

	public UserLoginAction() {
		super(true, false);
		setLoginPage(true);
	}

	/** Logger for this class. */
	private static final Logger logger = Logger
			.getLogger(UserLoginAction.class);

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 1L;

	/** The email. */
	private String email;

	/** The user id. */
	private String userId;

	/** The message. */
	private boolean message;

	private boolean remember;

	private boolean forget;

	private String redirectUri;

	/** The request. */
	private HttpServletRequest request;

	private HttpServletResponse response;

	/*
	 * (non-Javadoc)
	 *
	 * @see com.opensymphony.xwork2.ActionSupport#execute()
	 */
	@SuppressWarnings("unchecked")
	public String execute() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("execute() - start"); //$NON-NLS-1$
		}

		SearchCriteria searchCriteria = new SearchCriteria();
		searchCriteria.setAttribute(AttributeConstants.USER_ID, userName);
		searchCriteria.setAttribute(AttributeConstants.PASSWORD, password);
		List<User> userList = UserServiceDelegator.getList(searchCriteria);

		if (userList != null && userList.isEmpty() == false
				&& userList.get(0).getPassword().equals(password)) {
			User user = userList.get(0);
			if (user.getActive()) {
				Map<Object, Object> session = ActionContext.getContext()
						.getSession();
				session.put(AttributeConstants.USER, user);
				System.out.println(remember);
				if (remember) {
					Cookie userCookie = new Cookie(AttributeConstants.USER_ID, userName);
					Cookie passCookie = new Cookie(AttributeConstants.PASSWORD, CommonUtil.encrypt(password));
					userCookie.setMaxAge(31536000); // 60 * 60 * 24=86400 (1 day) *
					passCookie.setMaxAge(31536000);						// 365
					response.addCookie(userCookie);
					response.addCookie(passCookie);
				}

				if (logger.isDebugEnabled()) {
					logger.debug("execute() - end"); //$NON-NLS-1$
				}

				if(session.get("securedPage") != null) {
					this.redirectUri = session.get("securedPage").toString();
					session.remove("securedPage");
					return "redirectSuccess";
				}
				else {
					System.out.println("In else...");
					return SUCCESS;
				}
			} else {
				addActionError("Your account is still in pending.");
			}
		} else {
			addActionError("Invalid user name or password! Please try again!");
		}

		if (logger.isDebugEnabled()) {
			logger.debug("execute() - end"); //$NON-NLS-1$
		}
		return INPUT;
	}

	/**
	 * Logout.
	 *
	 * @return the string
	 *
	 * @throws Exception
	 *             the exception
	 */
	@SuppressWarnings("unchecked")
	public String logout() throws Exception {
		Map<Object, Object> session = ActionContext.getContext().getSession();
		session.put(AttributeConstants.USER, null);
		Cookie[] cookie = request.getCookies();

		for (int index = 0; index < cookie.length; index++) {
			if(cookie[index].getName().equals(AttributeConstants.USER_ID) || cookie[index].getName().equals(AttributeConstants.PASSWORD)) {
				cookie[index].setMaxAge( 0 );
				response.addCookie(cookie[index]);
			}
		}

		return SUCCESS;
	}

	/**
	 * Forgot user id.
	 *
	 * @return the string
	 *
	 * @throws Exception
	 *             the exception
	 */
	public String forgotUserId() throws Exception {
		this.userId = "true".intern();
		return SUCCESS;
	}

	/**
	 * Send user id.
	 *
	 * @return the string
	 *
	 * @throws Exception
	 *             the exception
	 */
	public String sendUserId() throws Exception {
//		if(Validator.isMailAddress(email)) {
			this.message = true;

			SearchCriteria searchCriteria = new SearchCriteria();
			searchCriteria.setAttribute(AttributeConstants.EMAIL, email);
			List<User> userList = UserServiceDelegator.getList(searchCriteria);

			if(userList.size() > 0) {
				User user = userList.get(0);
				addActionMessage("Your User Id Mail to your Email Address");
			} else {
				addActionMessage("Email address Not Found! <br>"+
					"Sorry, the email address you entered is not registered on our system. Please use the same email address you registered with on our system.");
			}
			/*	} else {
			this.userId = "true".intern();
			addActionError("Invalid e-mail address");
		}*/

		return SUCCESS;
	}

	/**
	 * Forgot password.
	 *
	 * @return the string
	 *
	 * @throws Exception
	 *             the exception
	 */
	public String forgotPassword() throws Exception {
		this.password = "true".intern();
		return SUCCESS;
	}

	/**
	 * Send password.
	 *
	 * @return the string
	 *
	 * @throws Exception
	 *             the exception
	 */
	public String sendPassword() throws Exception {
		this.message = true;

		SearchCriteria searchCriteria = new SearchCriteria();
		searchCriteria.setAttribute(AttributeConstants.USER_ID, userId);
		List<User> userList = UserServiceDelegator.getList(searchCriteria);

		if(userList.size() > 0) {
			User user = userList.get(0);
			addActionMessage("Your Password Mail to your Emial Address");
		} else {
			addActionMessage("User ID Not Found! <br>"+
					"Sorry, the User ID you entered is not registered on our system. Please use the same User ID you registered with on our system.");
		}

		return SUCCESS;
	}

	/**
	 * Activate user by activation id.
	 *
	 * @return the string
	 */
	public String activateUserByActivationId() {
		if (logger.isDebugEnabled()) {
			logger.debug("activateUserByActivationId() - start"); //$NON-NLS-1$
		}

		if (this.request.getParameter(AttributeConstants.ACTIVATION_CODE) != null) {
			SearchCriteria searchCriteria = new SearchCriteria();
			searchCriteria.setAttribute(AttributeConstants.ACTIVATION_CODE,
					this.request
							.getParameter(AttributeConstants.ACTIVATION_CODE));
			List<User> userList = UserServiceDelegator.getList(searchCriteria);

			if (userList.size() > 0) {
				User user = userList.get(0);
				user.setActive(true);
				UserServiceDelegator.updateUser(user);
				this.userName = user.getUserId();
				this.password = user.getPassword();

				if (logger.isDebugEnabled()) {
					logger.debug("activateUserByActivationId() - end"); //$NON-NLS-1$
				}
				return SUCCESS;
			} else {
				if (logger.isDebugEnabled()) {
					logger.debug("activateUserByActivationId() - end"); //$NON-NLS-1$
				}
				return ERROR;
			}
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("activateUserByActivationId() - end"); //$NON-NLS-1$
			}
			return AttributeConstants.LOGIN;
		}
	}

	/** The username. */
	private String userName = null;

	/** The password. */
	private String password = null;

	private Map cookieMap;

	/**
	 * Gets the username.
	 *
	 * @return the username
	 */
	public String getUserName() {
		return userName;
	}

	/**
	 * Sets the username.
	 *
	 * @param userName
	 *            the user name
	 */
	public void setUserName(String userName) {
		this.userName = userName;
	}

	/**
	 * Gets the password.
	 *
	 * @return the password
	 */
	public String getPassword() {
		return password;
	}

	/**
	 * Sets the password.
	 *
	 * @param password
	 *            the new password
	 */
	public void setPassword(String password) {
		this.password = password;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.apache.struts2.interceptor.ServletRequestAware#setServletRequest(javax.servlet.http.HttpServletRequest)
	 */
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	/**
	 * Gets the email.
	 *
	 * @return the email
	 */
	public String getEmail() {
		return email;
	}

	/**
	 * Sets the email.
	 *
	 * @param email
	 *            the new email
	 */
	public void setEmail(String email) {
		this.email = email;
	}

	/**
	 * Gets the user id.
	 *
	 * @return the user id
	 */
	public String getUserId() {
		return userId;
	}

	/**
	 * Sets the user id.
	 *
	 * @param userId
	 *            the new user id
	 */
	public void setUserId(String userId) {
		this.userId = userId;
	}

	/**
	 * Checks if is message.
	 *
	 * @return true, if is message
	 */
	public boolean isMessage() {
		return message;
	}

	/**
	 * Sets the message.
	 *
	 * @param message
	 *            the new message
	 */
	public void setMessage(boolean message) {
		this.message = message;
	}

	public boolean isRemember() {
		return remember;
	}

	public void setRemember(boolean remember) {
		this.remember = remember;
	}

	public boolean isForget() {
		return forget;
	}

	public void setForget(boolean forget) {
		this.forget = forget;
	}

	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	public String getRedirectUri() {
		return redirectUri;
	}
}